package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import com.itheima.utils.TransactionManager;

import java.util.List;

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;
    //private TransactionManager transactionManager;//已经由代理对象完成，此处不需要了
    //spring注入
    /*public  void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }*/

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public List<Account> findAllAccount() {
        List<Account> accounts= accountDao.findAllAccount();
        return accounts;
       /* try{
            //开启事务
            transactionManager.beginTransaction();
            //执行操作
            List<Account> accounts= accountDao.findAllAccount();
            //提交事务
            transactionManager.commitTransaction();
            //返回结果
            return accounts;
        }catch (Exception e){
            //回滚操作
            transactionManager.rollbackTransaction();
            throw new RuntimeException(e);
        }finally {
            //释放连接
            transactionManager.closeTransaction();
        }*/
    }
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }
    public void  deleteAccount(Integer acccountId) {
        accountDao.deleteAccount(acccountId);
    }
    public void transfer(String sourceName, String targerName, Float money) {
        try{
           // transactionManager.beginTransaction();
            //1根据名称查询转出账户
            Account source=accountDao.findAccountByName(sourceName);
            //2根据名称查询转入账户
            Account targer=accountDao.findAccountByName(targerName);
            //3传出账户减钱
            source.setMoney(source.getMoney()-money);
            //4转入账户加钱
            targer.setMoney(targer.getMoney()+money);
            //5更新转出账户
            accountDao.updateAccount(source);
            //int i=1/0;//让其手动添加爆出0做除数的异常。违反了数据事务的一致性，所有前面的都会执行，但是呢，就是不执行更新账户。
            // 因此，我们要把它们统一为一个connection对象。需要给加上ThreadLocal对象把conection对象和当前线程绑定，从而使一个线程只有一个能控制事务的对象。
            //事务的控制都是在业务层进行执行的。
            //6更新转入账户
            accountDao.updateAccount(targer);
            //transactionManager.commitTransaction();
        }catch (Exception e){
            //transactionManager.rollbackTransaction();
            throw  new RuntimeException(e);
        }finally {
           // transactionManager.closeTransaction();
        }
    }
}
